﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgressBar
{
    public partial class MyProgressBar : UserControl
    {
        private int minimum = 0;
        private int maximum = 100;
        private int value = 60;

        [Category("行为")]  //自定义属性，在属性窗口中分组
        public int Minimum
        {
            get => minimum;
            set { minimum = value; Invalidate(); }
        }

        [Category("行为")]
        public int Maximum
        {
            get => maximum;
            set { maximum = value; Invalidate(); }
        }

        [Category("行为")]
        public int Value
        {
            get => this.value;
            set
            {
                this.value = Math.Max(minimum, Math.Min(maximum, value));
                Invalidate(); // 触发重绘
            }
        }

        [Category("外观")]
        public Color ProgressColor { get; set; } = Color.DodgerBlue;
        public MyProgressBar()
        {
            this.DoubleBuffered = true;
            this.SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint |
                          ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
            this.Size = new Size(300, 30);
            InitializeComponent();
        }

        private void MyProgressBar_Load(object sender, EventArgs e)
        {

        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;

            float percent = (float)(value - minimum) / (maximum - minimum);
            int fillWidth = (int)(this.Width * percent);

            // 背景
            using (Brush bgBrush = new SolidBrush(Color.LightGray))
                g.FillRectangle(bgBrush, 0, 0, this.Width, this.Height);

            // 进度条
            using (Brush progressBrush = new SolidBrush(ProgressColor))
                g.FillRectangle(progressBrush, 0, 0, fillWidth, this.Height);

            // 显示百分比文字
            string text = $"{percent * 100}%";
            SizeF textSize = g.MeasureString(text, this.Font);
            using (Brush textBrush = new SolidBrush(Color.Black))
                g.DrawString(text, this.Font, textBrush, (this.Width - textSize.Width) / 2, (this.Height - textSize.Height) / 2);
        }
    }
}
